package com.web3.management.controller;

import com.web3.management.dto.ApiResponse;
import com.web3.management.dto.PageResponse;
import com.web3.management.dto.request.TradeLogBatchRequest;
import com.web3.management.dto.request.TradeLogRequest;
import com.web3.management.dto.response.TradeDailyStatsResponse;
import com.web3.management.dto.response.TradeLogResponse;
import com.web3.management.service.TradeLogService;
import lombok.RequiredArgsConstructor;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import java.time.LocalDate;
import java.util.List;

@RestController
@RequestMapping("/api")
@RequiredArgsConstructor
@Validated
public class TradeLogController {

    private final TradeLogService tradeLogService;

    @PostMapping("/trade-logs")
    public ApiResponse<TradeLogResponse> saveTradeLog(@Valid @RequestBody TradeLogRequest request) {
        TradeLogResponse response = tradeLogService.saveLog(request);
        return ApiResponse.success("日志记录成功", response);
    }

    @PostMapping("/trade-logs/batch")
    public ApiResponse<List<TradeLogResponse>> saveTradeLogs(@Valid @RequestBody TradeLogBatchRequest request) {
        List<TradeLogResponse> responses = tradeLogService.saveLogs(request.getLogs());
        return ApiResponse.success("批量日志记录成功", responses);
    }

    @GetMapping("/trade-logs")
    public ApiResponse<PageResponse<TradeLogResponse>> getTradeLogs(
            @RequestParam(required = false) Integer accountId,
            @RequestParam(required = false) Integer accountConfigId,
            @RequestParam(required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate startDate,
            @RequestParam(required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate endDate,
            @RequestParam(defaultValue = "1") @Min(1) Integer page,
            @RequestParam(defaultValue = "20") @Min(1) @Max(200) Integer size) {
        PageResponse<TradeLogResponse> response = tradeLogService.queryLogs(accountId, accountConfigId, startDate, endDate, page, size);
        return ApiResponse.success(response);
    }

    @GetMapping("/stats/trade/daily")
    public ApiResponse<List<TradeDailyStatsResponse>> getDailyStats(
            @RequestParam(required = false) Integer accountId,
            @RequestParam(required = false) Integer accountConfigId,
            @RequestParam(required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate startDate,
            @RequestParam(required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate endDate) {
        List<TradeDailyStatsResponse> stats = tradeLogService.getDailyStats(accountId, accountConfigId, startDate, endDate);
        return ApiResponse.success(stats);
    }
}
